package mystia.lorelei.app.service;

import jakarta.annotation.Resource;
import mystia.lorelei.app.entity.Employee;
import mystia.lorelei.app.repository.EmployeeRepository;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.sql.Date;
import java.time.LocalDate;
import java.util.List;


@Service
public class EmployeeService {
    @Resource
    private EmployeeRepository employeeRepository;

    public Page<Employee> listEmployeesByPage(String sex, String job, Boolean exited, Integer page, Integer size) {
        if (page <= 0) page = 1;
        if (size <= 0) size = 1;
        PageRequest request = PageRequest.of(page - 1, size);
        Employee employee = new Employee();
        employee.sex = sex;
        employee.job = job;
        employee.exited = exited;
        Example<Employee> employeeExample = Example.of(employee);
        return employeeRepository.findAll(employeeExample,request);
    }
    
    public List<Employee> listEmployee(){return employeeRepository.findAll();}
    
    public void saveEmployee(Employee employee) {
        if(employee.entryTime == null) {
            employee.entryTime = LocalDate.now();
        }
        if(employee.exited == null) {
            employee.exited = Boolean.FALSE;
        }
        employeeRepository.save(employee);
    }
    
    public void deleteEmployee(int id){
        employeeRepository.deleteById(id);
    }
    public void deleteEmployees(List<Integer> ids){
        employeeRepository.deleteAllByIds(ids);
    }
    
    public void updateExited(boolean exited, Date date, int id){
        employeeRepository.updateExitedById(exited,date,id);
    }
    
}
